<?php
namespace app\api\controller;
use app\api\model\ImageInfos;
use app\api\model\Likes;
use app\api\model\Movie;
use app\api\model\User;
use lib\AipOcr;
use lib\wechat\WxSmallClient;
use think\Controller;
use think\Db;
use think\Request;

class IndexController extends Controller
{
    public function index()
    {
        return $this->fetch('index');

    }
    public function baidus(){
        $movie = model('Movie');
        $data = $movie->limit(0,1)->select();
        foreach ($data as $v){
            if($v['stars_id']){
                $url = "http://api.douban.com/v2/movie/celebrity/1054395";
            }
        }
        var_dump($data);
    }
    public function open(){
        //待请求参数数组
        //$para = $this->buildRequestPara(['name'=>'sksks']);

        $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='https://maoyan.com/' method='post'>";
        /*while (list ($key, $val) = each ($para)) {
            $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
        }*/

        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml."<input type='submit' value='购票'></form>";

        $sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";

        return $sHtml;
    }

    /**
     * 测试登录
     */
    public function login(){
        $data= $this->request->param();
        if(!isset($data['iv']) || !$data['iv']){
            respon(0,'iv为空！');
        }
        if(!isset($data['code']) || !$data['code']){
            respon(0,'code为空！');
        }
        if(!isset($data['encryptedData']) || !$data['encryptedData']){
            respon(0,'encryptedData为空！');
        }
        $code = $data['code'];
        $iv = $data['iv'];
        $encryptedData = $data['encryptedData'];
        $result = WxSmallClient::getSessionKey($code);
        $array_user = json_decode($result);
        if (!is_object($array_user)) {
            respon(0, '网络异常请重试');
        }
        if ( property_exists($array_user, 'session_key')) {
            $userDatas = WxSmallClient::decryptData($array_user->session_key, $iv, $encryptedData);
            $userData = json_decode($userDatas, true);
            if (is_array($userData) && !empty($userData)) {
                $UserExtend = model('UserExtend');
                $user_info = $UserExtend->getOne(['ue_id','nickname','openid','avatar_url','phone'],['openid'=>$userData['openId']]);
                //$redis = new RedisDB(REDIS_URL,REDIS_PWD);
                $time = date("Y-m-d H:i:s",time());
                if(!$user_info){
                    $add_data = [
                        'nickname' => $userData['nickName'],
                        'openid' => $userData['openId'],
                        'unionid' => $userData['unionId'],
                        'gender' => $userData['gender'],
                        'province' => $userData['province'],
                        'city' => $userData['city'],
                        'avatar_url' => $userData['avatarUrl'],
                        'created_at'=> $time
                    ];
                    $res = $UserExtend::create($add_data);
                    if(!$res){
                        respon(0, '创建用户失败!');
                    }
                    $user_info = $add_data;
                    //$redis->setex($add_data['openid'],$token,72000);
                }else{
                    $UserExtend::update(['logined_at'=>$time],['openid'=>$user_info['openid']]);
                }
                $user_info['id'] = '';
                if(isset($user_info['phone'])){
                    $user = User::get(['phone'=>$user_info['phone']]);
                    $user_info['id'] = $user?$user['id']:'';
                }
                $this->redis->setnx($user_info['openid'],json_encode($user_info));
                respon(200,['user_info'=>$user_info]);
            }
        }else{
            respon(0, '网络异常请重试!');
        }
        /*$data= $this->request->param();
        var_dump($data['id']);exit;*/
        //$User = model('User');
        //$data = $User->getAlls(['phone'=>'185103241451111']);
        //var_dump($data);exit;
        //$data = $User->getOne(['id','phone'],['name'=>'xiaoming']);
        //limit($page,$pageSize)
        //$data = $User->where([])->order('id','DESC')->limit(1,2)->select();
        //添加数据
        //$data = $User::create(['phone'=>'18510324145121','age'=>123]);
        //更新数据
        /*$data = $User::update(['phone'=>'1851032414511111'],['id'=>100]);

        var_dump($data);exit;*/
    }


    /**
     * 首页
     */
    public function home(){
        $action = 'in_theaters?';
        $this->getMovies($action);
    }

    /**
     * 即将上映的
     */
    public function comming(){
        $action = 'coming_soon?';
        $this->getMovies($action);
    }

    /**
     * 搜索
     */
    public function search(){
        $action = 'search?';
        $this->getMovies($action);
    }

    /*
     * 影人搜索
     * **/
    public function search_figure(){
        $name=input('post.name');
        $where="fig_name like '%".$name."%'";

        $op=Db::name('figure')
            ->alias('fig')
            ->join('user_extend ue','fig.user_id = ue.ue_id','left')
            ->where($where)
            ->field('fig.id,fig.fig_name,fig.fig_job,fig.fig_company,fig.fig_achievement,ue.nickname,ue.ue_id,ue.gender,ue.province,ue.work,ue.avatar_url,ue.openid')
            ->select();
        if($op){
            return respon(200,$op);
        }else{
            return respon(240,'未查询到数据！');
        }
    }

    private function getMovies($action){
        $data= $this->request->param();
        if(!isset($data['start']) || !$data['start']){
            $data['start'] = 0;
        }
        if(!isset($data['count']) || !$data['count']){
            $data['count'] = 20;
        }
        if(isset($data['q']) && !empty($data['q'])){
            $q = $data['q'];
        }
        if(!is_numeric($data['start']) || !is_numeric($data['count'])){
            respon(0,'参数不合法!');
        }
        $city = isset($data['city'])?$data['city']:"";
        $param = ['start'=>$data['start'],'count'=>$data['count'],'city'=>$city];

        if(isset($q)){
            $param['q'] = $q;
        }
        $params = http_build_query($param);
        $url = RESOURCE_URL.$action.$params;
        //计算url的MD5摘要作为key
        $key = md5($url);
        $movie_info = $this->redis->get($key);
        if($movie_info){
            respon(200,json_decode($movie_info,true));
        }else{
            $data = curl($url);
            if($data){
                $datas = json_decode($data,true);
                if(isset($datas['code'])){
                    respon(0,$data['msg']);
                }else{
                    $this->redis->setex($key,$data,86400);
                    respon(200,$datas);
                }
            }
            respon(0,'暂无数据！');
        }
    }


    public function subject(){
        if(!input('openid')){
            return respon(230,'openid未获取到');
        }
        $user_info = json_decode($this->redis->get(input('openid')));
        if(!$user_info){
            respon(210,'用户信息错误！');
        }
        $data= $this->request->param();
        if(!isset($data['m_id']) || !$data['m_id']){
            respon(0,'缺少参数！');
        }
        if(!is_numeric($data['m_id'])){
            respon(0,'参数不正确！');
        }
        $url = SUBJECTS_URL.$data['m_id'];
        $key = 'key_'.$data['m_id'];
        //先从缓存中获取
        $detail = $this->redis->get($key);
        if($detail){
            respon(200,json_decode($detail,true));
        }
        $data = curl($url);
        if($data){
            if(isset($datas['code'])){
                respon(0,$data['msg']);
            }else{
                $datas = json_decode($data,true);
                //根据豆瓣id查询是否存在数据
                $douban_id = $datas['id'];
                $res = Movie::get(['douban_id'=>$douban_id]);
                //记录电影数据
                if($datas['casts']){
                    $casts_name = array_column($datas['casts'],'name');
                    $casts_id = array_column($datas['casts'],'id');
                    $stars = implode(' ',$casts_name);
                    $stars_id = implode(' ',$casts_id);
                }
                $pubdates = $datas['pubdates']?implode(' ',$datas['pubdates']):'';
                $genres = implode(' ',$datas['genres']);
                $add_data = [
                    'name'=>$datas['title'],
                    'descriptions'=>$datas['summary'],
                    'type'=>$genres,
                    'duration'=>$datas['durations'][0],
                    'movie_image'=>$datas['images']['large'],
                    'initial_release_date'=>$pubdates,
                    'douban_url'=>$datas['alt'],
                    'douban_id' =>$douban_id,
                    'rate'=>($datas['rating']['average'])*10,
                    'original_name'=>$datas['original_title'],
                    'directed'=>$datas['directors'][0]['name'],
                    'en_directed'=>$datas['directors'][0]['name_en'],
                    'directed_id'=>$datas['directors'][0]['id'],
                    'stars'=>$stars,
                    'stars_id'=>$stars_id
                ];
                if(!$res){
                    $res = Movie::create($add_data);
                }else{
                    Movie::update($add_data,['douban_id'=>$douban_id]);
                }
                $movie_id = $res['id'];
                $datas['movie_id'] = $movie_id;
                $user_id = $user_info->id;
                //添加足迹记录
                $this->addFootPoint($user_id,$movie_id);
                $this->redis->set($key,json_encode($datas));
                respon(200,$datas);
            }
        }

    }

    private function addFootPoint($user_id,$movie_id){
        $res = db('footprint')->insert(['fp_conid' =>$movie_id,'fp_user_id'=>$user_id,'fp_type'=>1]);
    }



    /**
     * @desc  发送短信验证码
     * @param $phone
     * @param string $msg
     * @return array
     * 生产，发送短信验证码并存入到验证码表中
     * $phone  手机号
     * $extime=300秒 有效时间设置为300秒
     * $resend_time=60秒  重新发送时间为60秒
     */
    public function sendCode($phone,$msg=''){
        if(empty($phone)) return false;
        $dbo = Db::name('phone_msg')->where(['phone'=>$phone])->field('create_time')->find();
        $newtime=time();
        if($newtime - $dbo['create_time'] <60){
            return respon(201,'两次验证码间隔未超过60秒，请您稍后再试！');
        }
        $msgCode = rand(234567,987654);
        //$msg = str_replace('__CON__',$msgCode,$msg);
        $msg = '您的验证码是：【'.$msgCode.'】。请不要把验证码泄露给其他人。如非本人操作，可不用理会！';
        $data=['phone'=>$phone,
            'phone_msg'=>$msgCode,
            'create_time'=>time(),
            'exp_time'=>time()+300,
        ];
        if($dbo){
            $where='phone = '.$phone;
            $result=Db::name('phone_msg') ->where($where)->update($data);
        }else{
            $result=Db::name('phone_msg') ->insert($data);
        }
        if($result){
            $res = send_msg($phone,$msg);
            if($res['result']){
                respon(200,'发送成功！');
            }
        }
        respon(0,'发送失败！');
    }


    //统计操作发放token
    public function tokens(){
        //统计每天注册的用户
        //$this->getRegister();
        $this->getReview(1);
    }

    //每天注册的用户
    private function getRegister(){
        $result=Db::name('user')->where($this->where)->field('content')->select();
        var_dump($result);
    }

    //每天发布短评的用户
    private function getReview($type){
        $this->where['type']=$type;
        $result=Db::name('film_review')->where($this->where)->field('')->select();
        var_dump($result);
    }
}